package de.velvettear.squirrel.gui;

import java.util.Vector;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.Toast;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.adapter.PasswordGeneratorAdapter;
import de.velvettear.squirrel.database.DatabaseHelper;
import de.velvettear.squirrel.kernel.Password;
import de.velvettear.squirrel.kernel.Return;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.CameraHelper;
import de.velvettear.squirrel.util.ClipboardHelper;
import de.velvettear.squirrel.util.EncryptionHelper;
import de.velvettear.squirrel.util.PasswordHelper;

public class PasswordsFrame extends FragmentActivity implements ActionBar.TabListener {
			
	private static ViewPager viewPager;
	private static SectionsPagerAdapter sectionsPagerAdapter;	
		
	// PasswordGenerator-Fragment
	private PasswordGeneratorAdapter passwordGeneratorAdapter;
	private boolean generatingPasswords;
	private boolean generatedPasswords;
	
	private static LinearLayout ll_background;
	private static CheckBox cb_lowercase;
	private static CheckBox cb_uppercase;
	private static CheckBox cb_numeric;
	private static CheckBox cb_specialcharacters;
	private static NumberPicker np_length;
	private static NumberPicker np_quantity;
	private static LinearLayout ll_lv_passwordgenerator;
	private static ListView lv_passwordgenerator;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_networkframe);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setAdapter(sectionsPagerAdapter);

		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
			actionBar.newTab();
		}	
						
	}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		getMenuInflater().inflate(R.menu.menu_securityframe, menu);	
		
		if (generatingPasswords) {
			menu.removeItem(R.id.menu_securityframe_start);
		} else {
			menu.removeItem(R.id.menu_securityframe_stop);
		}
		
		if (!generatedPasswords) {
			menu.removeItem(R.id.menu_securityframe_reset);
		}
		
		return super.onCreateOptionsMenu(menu);	
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
				
		case R.id.menu_securityframe_start:
			generatePasswords();
			break;
		
		case R.id.menu_securityframe_stop:
			generatingPasswords = false;
			invalidateOptionsMenu();
			break;
			
		case R.id.menu_securityframe_reset:
			switchPasswordGeneratorView(false);		
			break;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		invalidateOptionsMenu();
		viewPager.setCurrentItem(tab.getPosition());
		
//		if (getCurrentFragment() == Statics.ID_SECURITYFRAGMENT_PASSWORDSTORE) {
//			CameraHelper.takeFrontPicture();
//		}
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}
		
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);						
	}
	
	private static int getCurrentFragment() {
		return (int) sectionsPagerAdapter.getItemId(viewPager.getCurrentItem());
	}
		
	private void generatePasswords() {
		generatingPasswords = true;
		invalidateOptionsMenu();
		
		AsyncTask<Void, Void, Return> generatePasswordsTask = new AsyncTask<Void, Void, Return>() {

			@Override
			protected Return doInBackground(Void... params) {
				
				Vector<Password> passwords = new Vector<Password>();
				Return ret = new Return();
					for (int count = 0; count < np_quantity.getValue(); count++) {
						if (generatingPasswords) {
							Password pass = PasswordHelper.generatePassword(np_length.getValue(), cb_lowercase.isChecked(), cb_uppercase.isChecked(), cb_numeric.isChecked(), cb_specialcharacters.isChecked());
							passwords.add(pass);
						} else {
							ret.m_bSuccess = false;
							ret.m_sMessage = "Process canceled!";
							return ret;
						}
					}
					ret.m_bSuccess = true;
					ret.m_cData = passwords;
							
				return ret;
			}
			
			@Override
			protected void onPostExecute(Return ret) {		
				generatingPasswords = false;
				invalidateOptionsMenu();
				if (ret.m_bSuccess) {
					fillPasswordGeneratorList((Vector<Password>) ret.m_cData);
				} else {
					Toast.makeText(getApplicationContext(), ret.m_sMessage, Toast.LENGTH_SHORT).show();
				}
			}
			
		};
		
		generatePasswordsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	
	private void fillPasswordGeneratorList(Vector<Password> passwords) {		
		if (lv_passwordgenerator.getAdapter() != null) {
			lv_passwordgenerator.setAdapter(null);
		}
		
		passwordGeneratorAdapter = new PasswordGeneratorAdapter(getApplicationContext(), R.layout.listview_passwordgenerator, R.id.listview_passwordgenerator_value, passwords);
		
		lv_passwordgenerator.setAdapter(passwordGeneratorAdapter);		
		switchPasswordGeneratorView(true);
	}
	
	private void switchPasswordGeneratorView(boolean m_bResults) {		
		if (m_bResults) {
			generatedPasswords = true;
			ll_background.setVisibility(View.GONE);
			ll_lv_passwordgenerator.setVisibility(View.VISIBLE);			
		} else {
			generatedPasswords = false;
			ll_lv_passwordgenerator.setVisibility(View.GONE);
			ll_background.setVisibility(View.VISIBLE);
			lv_passwordgenerator.setAdapter(null);
		}
		invalidateOptionsMenu();
	}
	
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			
			case 0: return PasswordGeneratorFragment.newInstance();
			case 1: return PasswordStoreFragment.newInstance();
			
			default: return PasswordGeneratorFragment.newInstance();
			
			}
		}

		@Override
		public int getCount() {	
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return Statics.PASSWORD_GENERATOR;
			case 1:
				return Statics.PASSWORD_STORE;
			}
			return null;
		}
	}
		
	public static class PasswordGeneratorFragment extends Fragment implements OnItemLongClickListener {
						
		public PasswordGeneratorFragment() {
		
		}

		public static PasswordGeneratorFragment newInstance() {
			PasswordGeneratorFragment fragment = new PasswordGeneratorFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_passwordgenerator, container, false);
			
			ll_background = (LinearLayout) rootView.findViewById(R.id.passwordgenerator_ll_background);
			cb_lowercase = (CheckBox) rootView.findViewById(R.id.passwordgenerator_cb_lowercase);
			cb_uppercase = (CheckBox) rootView.findViewById(R.id.passwordgenerator_cb_uppercase);
			cb_numeric = (CheckBox) rootView.findViewById(R.id.passwordgenerator_cb_numeric);
			cb_specialcharacters = (CheckBox) rootView.findViewById(R.id.passwordgenerator_cb_specialcharacters);
					
			np_length = (NumberPicker) rootView.findViewById(R.id.passwordgenerator_np_length);
			np_length.setMaxValue(Statics.NUMBERPICKER_PASSWORDLENGTH_MAX);
			np_length.setMinValue(Statics.NUMBERPICKER_PASSWORDLENGTH_MIN);
			np_length.setValue(Statics.NUMBERPICKER_PASSWORDLENGTH_DEFAULT);
			np_quantity = (NumberPicker) rootView.findViewById(R.id.passwordgenerator_np_quantity);
			np_quantity.setMaxValue(Statics.NUMBERPICKER_PASSWORDQUANTITY_MAX);
			np_quantity.setMinValue(Statics.NUMBERPICKER_PASSWORDQUANTITY_MIN);
			np_quantity.setValue(Statics.NUMBERPICKER_PASSWORDQUANTITY_DEFAULT);
			
			ll_lv_passwordgenerator = (LinearLayout) rootView.findViewById(R.id.passwordgenerator_ll_listview);	
			lv_passwordgenerator = (ListView) rootView.findViewById(R.id.passwordgenerator_lv);				
			lv_passwordgenerator.setOnItemLongClickListener(this);
			
			return rootView;
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
			
			Password pass = (Password) lv_passwordgenerator.getAdapter().getItem(position);
			pass.m_sValue = EncryptionHelper.encrypt(pass.m_sValue);			
			
			pass.store();
						
			ClipboardHelper.copyToClipboard(pass.m_sValue);
			Toast.makeText(getActivity(), "Password copied!", Toast.LENGTH_SHORT).show();
			
			return false;
		}

				
	}
	
	public static class PasswordStoreFragment extends Fragment {
			
		public PasswordStoreFragment() {
		
		}

		public static PasswordStoreFragment newInstance() {
			PasswordStoreFragment fragment = new PasswordStoreFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_passwordstore, container, false);
								
			fillPasswordStoreList();
			
			return rootView;
		}
		
		private void fillPasswordStoreList() {
			Password p = new Password();
			p.m_sValue = "derp";
			p.m_sName = "TWITTER";
			p.store();
			
			p = new Password();
			p.m_sValue = "1213452135";
			p.m_sName = "Facebook";
			p.store();
			
			Vector<Password> passwords = new Password().select(null, null, false);
		}
		
	}

}
